package top.hmtools.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import top.hmtools.RLContext;
import top.hmtools.base.StringTools;
import top.hmtools.common.StaticContent;
import top.hmtools.pojo.RequestLogBean;

import com.alibaba.fastjson.JSON;

/**
 * 接收埋点日志相关的control
 * 
 * @author Hybo
 * 
 */
@Controller
@ConditionalOnProperty(prefix=StaticContent.CONFIG_PREFIX,value=StaticContent.CONFIG_ITEM_KEY_NAME_ENABLED,matchIfMissing=true)
public class RequestLoggerController {

	protected final Logger logger = LoggerFactory.getLogger(RequestLoggerController.class);
	
	@Autowired
	private RLContext rlContext;

	/**
	 * 获取用户页面停留时间，并更新到对应的 访问日志记录
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="${"+StaticContent.CONFIG_PREFIX+"."+StaticContent.CONFIG_ITEM_KEY_NAME_APPEND_EXTRA_LOG_URI+":/appendExtraLog}")
	public String appendExtraLog(HttpServletRequest request,HttpServletResponse response){
		String result = null;
		try {
			String requestID = request.getParameter("requestID");
			String callbackFunName =request.getParameter("callbackparam");//得到js函数名称，用于处理跨域异步请求
			String duration =request.getParameter("duration");//得到 用户页面停留时长  数据
			String visitorID =request.getParameter("visitorID");//得到 终端的 访问者ID
			
			logger.debug("requestID："+requestID);
			logger.debug("duration："+duration);
			logger.debug("visitorID："+visitorID);
			
			if(StringTools.isBlank(requestID) || StringTools.isBlank(duration)){
				return result;
			}
			
			//组装请求记录
			RequestLogBean logBean = new RequestLogBean();
			logBean.setRequestID(requestID);
			logBean.setResidenceTime(Long.valueOf(duration));
			logBean.setVisitorID(visitorID);
			
			//追加对应的扩展请求记录
			this.rlContext.requestLoggerManager.addRequestLoggerBeanExtraToQueue(logBean);
			
			Map<String,String> map = new HashMap<String,String>();
			
			result = callbackFunName + "([ "+JSON.toJSONString(map)+"])";
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(),e);
		}
		
		return result;
	}
}
